<template>
	<div class="content" v-loading="loading">
		<el-form ref="form" :model="form" :rules="rules" label-width="130px">
			<div class="form-group">
				<el-form-item label="商品链接：" style="width: 94%">
					<el-input
						v-model="form.link"
						size="small"
						clearable
						placeholder="请填写商品链接"
					></el-input>
				</el-form-item>
				<el-button type="primary" class="search-btn" size="small" @click="onSearchGoods"
					>检索</el-button
				>
			</div>
			<el-form-item label="商品信息：" v-if="goodsInfo.gid">
				<div class="goods-info">
					<div class="top">
						<div class="img-box">
							<img :src="goodsInfo.productPicUrl" />
						</div>
						<div class="right">
							<div class="title-sale">
								<p class="title">{{ goodsInfo.productTitle }}</p>
								<p class="sale">月销量：{{ goodsInfo.sale }}</p>
							</div>
							<p class="shop">{{ goodsInfo.productShopName }}</p>
							<p class="gid">商品ID：{{ goodsInfo.gid }}</p>
							<div class="price">
								<p class="old">
									原价：<span>{{ goodsInfo.price }}元</span>
								</p>
								<p class="coupon">
									券面额：<span>{{ goodsInfo.couponMoney }}元券</span>
								</p>
								<p class="coupon">
									券后价：<span>{{ goodsInfo.endPrice }}元</span>（{{
										goodsInfo.couponConditions
									}}）
								</p>
							</div>
							<p class="time">
								优惠券有效期：{{ goodsInfo.couponStarttime }} ~
								{{ goodsInfo.couponEndtime }}
							</p>
						</div>
					</div>
					<div class="center" v-if="goodsInfo.taobaoImageList.length > 0">
						<img :src="item" v-for="item in goodsInfo.taobaoImageList" :key="item" />
					</div>
					<div class="coupon-list">
						<p class="money">
							优惠券金额：<span>{{ goodsInfo.couponMoney }}</span>
						</p>
						<p class="num">
							优惠券数量：<span>{{ goodsInfo.couponNum }}</span>
						</p>
						<p class="num">
							已领取数量：<span>{{ goodsInfo.couponReceive }}</span>
						</p>
					</div>
					<p class="coupon-id">
						优惠券ID：<span>{{ goodsInfo.activityId }}</span
						><i
							class="el-icon-copy-document"
							v-copy="goodsInfo.activityId"
							style="cursor: pointer"
						></i>
					</p>
				</div>
			</el-form-item>
			<el-form-item label="商品标题：" prop="title">
				<el-input
					v-model="form.title"
					clearable
					size="small"
					placeholder="请填写商品标题"
				></el-input>
			</el-form-item>
			<el-form-item label="商品名称：" prop="name">
				<el-input
					v-model="form.name"
					clearable
					size="small"
					placeholder="请填写商品名称"
				></el-input>
			</el-form-item>
			<el-form-item label="商品描述：" prop="brief">
				<el-input
					v-model="form.brief"
					clearable
					size="small"
					placeholder="请填写商品描述"
				></el-input>
			</el-form-item>
			<el-form-item label="商品图片：" prop="pic">
				<cl-upload v-model="form.pic"></cl-upload>
			</el-form-item>

			<!--            <el-form-item label="券链接：" prop="couponUrl">-->
			<!--                <el-input-->
			<!--                        v-model="form.couponUrl"-->
			<!--                        size="small"-->
			<!--                        clearable-->
			<!--                        placeholder="请填写券链接"-->
			<!--                ></el-input>-->
			<!--            </el-form-item>-->
			<!--            <el-form-item label="商品图片：" style="width: 40%" prop="profitRate">-->
			<!--                <el-input-->
			<!--                        v-model="form.profitRate"-->
			<!--                        size="small"-->
			<!--                        clearable-->
			<!--                        placeholder="请填写拼团让利"-->
			<!--                        @change="onProfitChange"-->
			<!--                ></el-input>-->
			<!--            </el-form-item>-->
			<el-form-item label="奖励总单数：" style="width: 50%">
				<el-input-number
					v-model="form.effectiveNum"
					style="width: 100%"
					:precision="0"
					size="small"
					:step="1"
					:min="1"
				></el-input-number>
			</el-form-item>
			<el-form-item label="单个奖励金币：" style="width: 50%">
				<el-input-number
					v-model="form.goldAmount"
					style="width: 100%"
					:precision="1"
					size="small"
					:step="0.5"
					:min="1"
				></el-input-number>
			</el-form-item>
			<el-form-item label="商品排序：" style="width: 50%">
				<el-input-number
					v-model="form.level"
					style="width: 100%"
					:precision="0"
					size="small"
					:step="1"
					:min="1"
				></el-input-number>
			</el-form-item>
			<el-form-item label="商品状态：" style="width: 50%">
				<el-switch
					v-model="form.status"
					:active-value="1"
					:inactive-value="0"
					active-text="商品上线"
					inactive-text="商品下架"
				>
				</el-switch>
			</el-form-item>
			<el-form-item label="精编素材文案：" style="width: 50%">
				<el-switch v-model="form.isEditor" :active-value="1" :inactive-value="0">
				</el-switch>
			</el-form-item>
		</el-form>
		<div
			id="editorElem"
			class="editor-elem"
			style="text-align:left;"
			v-show="parseInt(form.isEditor) === 1"
		></div>
		<div class="footer-bar">
			<el-button type="primary" @click="onSubmit()">发布商品</el-button>
		</div>
	</div>
</template>

<script>
import moment from 'moment';
import E from 'wangeditor';
export default {
	name: 'add',
	data() {
		return {
			loading: false,
			goodsInfo: {},
			form: {
				link: '',
				title: '',
				name: '',
				brief: '',
				pic: '',
				effectiveNum: 1,
				goldAmount: 1,
				level: 1,
				status: 1,
				isEditor: 0,
				detailMsg: ''
			},
			rules: {
				title: [{ required: true, message: '商品标题不能为空', trigger: 'blur' }],
				name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
				brief: [{ required: true, message: '商品描述不能为空', trigger: 'blur' }],
				pic: [{ required: true, message: '商品图片不能为空', trigger: 'blur' }]
			},
			editor: null
		};
	},
	activated() {
		if (this.$route.query.id) {
			this.loading = true;
			this.$service.promotion.goods
				.info({
					id: this.$route.query.id
				})
				.then(res => {
					this.form.link = res.link;
					this.form.title = res.title;
					this.form.name = res.name;
					this.form.brief = res.brief;
					this.form.pic = res.pic;
					this.form.effectiveNum = res.effectiveNum;
					this.form.goldAmount = res.goldAmount;
					this.form.level = res.level;
					this.form.status = res.status;
					this.form.isEditor = res.isEditor;
					this.form.detailMsg = res.detailMsg;
					this.loading = false;

					if (this.$route.query.id) {
						setTimeout(() => {
							this.editor.txt.html(this.form.detailMsg);
						}, 2000);
					}
				});
		}
	},
	mounted() {
		let that = this;
		this.editor = new E('#editorElem');

		this.editor.config.onchange = html => {
			// let text = this.editor.txt.text();
			this.form.detailMsg = html;
			// console.log(text);
			// console.log(html);
		};
		const upload = this.$service.common.upload();
		this.editor.config.onchangeTimeout = 200;
		this.editor.config.uploadImgHeaders = {
			Authorization: this.$store.state.user.token
		};
		this.editor.config.uploadFileName = 'file'; //上传参数 自定义
		this.editor.config.uploadImgServer = upload.url; // 上传图片
		// 监听
		this.editor.config.uploadImgHooks = {
			// before: function(xhr, editor, files) {
			// 	// 图片上传之前触发
			// },
			// success: function(xhr, editor, result) {
			// 	// 图片上传并返回结果，图片插入成功之后触发
			// },
			// fail: function(xhr, editor, result) {
			// 	console.log('插入图片失败！');
			// },
			// error: function(xhr, editor) {
			// 	console.log('插入图片失败！');
			// },
			// timeout: function(xhr, editor) {
			// 	console.log('插入图片失败！');
			// },
			customInsert: function(insertImg, result) {
				that.$service.promotion.goods
					.uploadPic({
						url: result.data
					})
					.then(res => {
						insertImg(res);
					});
			}
		};
		this.editor.create();
	},
	methods: {
		onSearchGoods() {
			if (!this.form.link) {
				this.$message.error('商品链接不能为空');
				return false;
			}
			this.$service.coupon.record
				.goodsInfo({
					product_url: this.form.link
				})
				.then(res => {
					this.goodsInfo = res;

					this.goodsInfo.couponStarttime = moment(
						this.goodsInfo.couponStarttime * 1000
					).format('YYYY-MM-DD HH:mm:ss');
					this.goodsInfo.couponEndtime = moment(
						this.goodsInfo.couponEndtime * 1000
					).format('YYYY-MM-DD HH:mm:ss');
					this.goodsInfo.taobaoImageList = this.goodsInfo.taobaoImage.split(',');

					this.form.title = this.goodsInfo.shortTitle;
					this.form.name = this.goodsInfo.shortTitle;
					this.form.brief = this.goodsInfo.desc;
					this.form.pic = this.goodsInfo.productPicUrl + '_300x300.jpg';
				})
				.catch(() => {
					this.$message.error('未检索到商品');
					this.goodsInfo = {};
				});
		},
		onSubmit() {
			if (this.$route.query.id) {
				this.$refs['form'].validate(valid => {
					if (valid) {
						let params = {
							id: this.$route.query.id,
							...this.form
						};
						this.$service.promotion.goods.update(params).then(() => {
							this.$message.success('修改成功');

							this.$router.push('/single/manage');
						});
					}
				});
			} else {
				if (!this.goodsInfo.gid) {
					this.$message.error('请先检索商品');
					return false;
				}
				this.$refs['form'].validate(valid => {
					if (valid) {
						let params = {
							...this.goodsInfo,
							...this.form,
							gid: this.goodsInfo.gid,
							shopName: this.goodsInfo.shopName,
							shoptype: this.goodsInfo.shoptype
						};
						this.$service.promotion.goods
							.add(params)
							.then(() => {
								this.$message.success('发布成功');

								this.$router.push('/single/manage');
							})
							.catch(err => {
								this.$message.error(err);
							});
					}
				});
			}
		}
	}
};
</script>

<style lang="stylus" scoped>
.content {
    background: #fff;
    padding: 10px 20px;
    height: 100%;
    overflow-y: auto;
    .goods-info {
        color #333
        p {
            line-height 24px;
        }
        .top {
            flexBox(space-between, center);
            .img-box {
                width 150px;
                height 150px;
                img {
                    width 100%
                    height 100%
                }
            }
            .right {
                flex 1;
                height 150px;
                overflow auto;
                margin-left 20px;
                flexBox(space-between, flex-start, column);
                .title-sale {
                    width 100%
                    flexBox(space-between, center);
                    .sale {
                        color #999999
                    }
                }
                .gid, .shop, .time {
                    color #999999
                }
                .price {
                    width 100%
                    flexBox(space-between, center);
                    span {
                        color red
                    }
                }
            }
        }
        .center {
            width 100%
            padding 10px 50px
            flexBox(space-around, center);
            img {
                width 80px;
                height 80px
                margin 10px
                border 1px solid #ccc
            }
        }
        .coupon-list {
            width 100%
            flexBox(space-between, center);
            span {
                color red
            }
        }
        .coupon-id {
            span {
                color red
                margin-right 10px
            }
        }
    }
    /deep/.el-form {
        width: 70%;
    }
    .form-group {
        display flex
        .search-btn {
            height 30px
            margin-top 5px
            margin-left 10px
        }
    }
    .editor-elem {
        height 350px
        width 70%
    }
    .footer-bar {
        width 70%
        text-align center
        padding  20px 0
    }
}
</style>
